# -*- coding: utf-8 -*- 
# excelreader.py
# read excel write cpp

import xlrd
import os
import struct
import sys
import hwriter
import cppfilewriter

cppfile = cppfilewriter.cppfilewriter()
hfile = hwriter.hwriter()

EXCEL_FILE_END = '.xls'

EXCEL_FORMAT_LIST        =      0
EXCEL_FORMAT_NAME_LIST   =      1
EXCEL_REAL_BEGIN         =      3

def read_table(table,tablename):
    nrows = table.nrows
    ncols = table.ncols
    format_list = table.row_values(EXCEL_FORMAT_LIST)
    format_name_list = table.row_values(EXCEL_FORMAT_NAME_LIST)
    print "Param Format :",format_list,"   type :",format_name_list

    

    #write bytes file
    for i in range(EXCEL_REAL_BEGIN,nrows):
        print "value====",table.row_values(i)
        
    #.h 
    hfile.add_class_class(tablename)
    hfile.add_class_var(format_list,format_name_list)
    hfile.add_end()
    hfile.add_table_class(tablename)

    #.cpp
    cppfile.add_class_func(tablename,format_list)
    cppfile.add_table_func(tablename)
   
        

def read_file(filename):
    book = xlrd.open_workbook(filename,'r')
    for i in range(book.nsheets):
        tablename = book.sheet_names()[i]
        print "Reading table :" ,tablename
        read_table(book.sheets()[i],tablename)

def read_all_excel():
    dir = os.getcwd()
    hfile.write_import()
    cppfile.write_import()
    for root,dirs,filename in os.walk(dir):
        for file in filename:
            path_filename = os.path.join(root,file)
            if path_filename.endswith(EXCEL_FILE_END):
                print "Reading file :",path_filename
                read_file(path_filename)

def check_dir():
    if(not (os.path.isdir("code"))):
        os.mkdir("code")

if __name__=="__main__":
    reload(sys)
    sys.setdefaultencoding('utf-8')
    check_dir()
    read_all_excel()
